<template>
  <div>
    <v-centerForm>
      <template slot='left'>
        <el-form inline :model="searchObject" ref="searchObject" label-width="80px">
          <el-form-item label="原文件名"
                        prop="fileName">
            <el-input placeholder="请输入原文件名" v-model="searchObject.fileName"></el-input>
          </el-form-item>
          <el-form-item label="存储桶名"
                        prop="bucketName">
            <el-input placeholder="请输入存储桶名" v-model="searchObject.bucketName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" icon="el-icon-search" type="primary" @click="search">搜索</el-button>
            <el-button size="mini" icon="el-icon-refresh-left" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template slot='right'>
        <el-upload :action="importUrl"
                   :show-file-list="false"
                   :on-success="handleImportFile" style="display: inline-block">
          <el-button size="mini" type="primary" icon="el-icon-top" style="margin-left: 10px">导入
          </el-button>
        </el-upload>
        <el-button size="mini" type="warning" icon="el-icon-bottom" style="margin-left: 10px" @click="handleExportFile">
          导出
        </el-button>
        <el-button size="mini" icon="el-icon-delete" type="danger" @click="removeBatchDialog"
                   :disabled="tableSelectData.length === 0">批量删除
        </el-button>
      </template>
    </v-centerForm>
    <x-table :loading="loadingBtn.tableLoading" :columnData="columnData" :tableData="tableData"
             :tableSize="pagination.size" :tableTotal="pagination.total" @currentPage="getCurrent" @pageSize="getSize"
             @selectionChange="selectionChange">
      <el-table-column slot="selection" :selectable="row=>!row.init" type="selection" align="center">
      </el-table-column>
      <el-table-column show-overflow-tooltip @click="copyText(scope.row.fileUrl)" slot="fileUrl"
                       label="文件URL"
                       align="center">
        <template slot-scope="scope">
          <div @click="copyText(scope.row.fileUrl)">{{ scope.row.fileUrl }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" slot="operate" label="操作选项" width="200">
        <template slot-scope="scope" v-if="!scope.row.init">
          <el-tooltip class="item" effect="dark" content="新增" placement="top">
            <i class="el-icon-circle-plus-outline table-icon-btn color-primary"
               @click="addOrSeeOrEdit('新增','add', scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="查看" placement="top">
            <i class="el-icon-view table-icon-btn color-success" @click="addOrSeeOrEdit('查看','see', scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="el-icon-edit-outline table-icon-btn color-primary"
               @click="addOrSeeOrEdit('编辑','edit', scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="el-icon-delete table-icon-btn color-error" @click="removeDialog(scope.row)"></i>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="下载" placement="top">
            <i class="el-icon-download table-icon-btn color-warning"
               @click="download(scope.row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </x-table>
    <el-dialog :title="dialog.title" :visible.sync="dialogVisible" @closed="closeDialog">
      <el-form :disabled="dialog.flag === 'see'" :model="form" ref="form" :rules="rules" :label-width="formLabelWidth">
        <el-form-item label="分片上传的uploadId" prop="uploadId">
          <el-input v-model="form.uploadId" placeholder="请输入分片上传的uploadId"></el-input>
        </el-form-item>
        <el-form-item label="文件唯一标识（md5）" prop="fileIdentifier">
          <el-input v-model="form.fileIdentifier" placeholder="请输入文件唯一标识（md5）"></el-input>
        </el-form-item>
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名"></el-input>
        </el-form-item>
        <el-form-item label="所属桶名" prop="bucketName">
          <el-input v-model="form.bucketName" placeholder="请输入所属桶名"></el-input>
        </el-form-item>
        <el-form-item label="文件的key" prop="objectKey">
          <el-input v-model="form.objectKey" placeholder="请输入文件的key"></el-input>
        </el-form-item>
        <el-form-item label="文件URL" prop="fileUrl">
          <el-input v-model="form.fileUrl" placeholder="请输入文件URL"></el-input>
        </el-form-item>
        <el-form-item label="文件大小（byte）" prop="totalSize">
          <el-input v-model="form.totalSize" placeholder="请输入文件大小（byte）"></el-input>
        </el-form-item>
        <el-form-item label="每个分片大小（byte）" prop="chunkSize">
          <el-input v-model="form.chunkSize" placeholder="请输入每个分片大小（byte）"></el-input>
        </el-form-item>
        <el-form-item label="分片数量" prop="chunkNum">
          <el-input v-model="form.chunkNum" placeholder="请输入分片数量"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import fileApi from '@/api/upload/fileApi'
import { axiosBaseUrl } from '@/common/config/baseConfig'
import xTable from '@/components/xTable/x-table'

export default {
  name: 'fileList',
  components: { xTable },
  data () {
    return {
      importUrl: axiosBaseUrl + '/api/v1/file/importFile',
      exportUrl: axiosBaseUrl + '/api/v1/file/exportFile',
      loadingBtn: {
        tableLoading: false
      },
      searchObject: {},
      tableData: [],
      tableSelectData: [],
      columnData: [
        {
          slot: 'selection'
        },
        {
          type: 'index',
          label: '序号'
        },
        {
          label: '分片上传的uploadId',
          prop: 'uploadId'
        },
        {
          label: '文件唯一标识（md5）',
          prop: 'fileIdentifier'
        },
        {
          label: '文件名',
          prop: 'fileName'
        },
        {
          label: '所属桶名',
          prop: 'bucketName'
        },
        {
          label: '文件的key',
          prop: 'objectKey'
        },
        {
          label: '文件URL',
          slot: 'fileUrl'
        },
        {
          label: '文件大小（byte）',
          prop: 'totalSize'
        },
        {
          label: '每个分片大小（byte）',
          prop: 'chunkSize'
        },
        {
          label: '分片数量',
          prop: 'chunkNum'
        },
        {
          slot: 'operate',
          label: '操作选项'
        }
      ],
      rules: {
        uploadId: [
          {
            required: true,
            message: '分片上传的uploadId不能为空',
            trigger: 'blur'
          }
        ],
        fileIdentifier: [
          {
            required: true,
            message: '文件唯一标识（md5）不能为空',
            trigger: 'blur'
          }
        ],
        fileName: [
          {
            required: true,
            message: '文件名不能为空',
            trigger: 'blur'
          }
        ],
        bucketName: [
          {
            required: true,
            message: '所属桶名不能为空',
            trigger: 'blur'
          }
        ],
        objectKey: [
          {
            required: true,
            message: '文件的key不能为空',
            trigger: 'blur'
          }
        ],
        fileUrl: [
          {
            required: true,
            message: '文件URL不能为空',
            trigger: 'blur'
          }
        ],
        totalSize: [
          {
            required: true,
            message: '文件大小（byte）不能为空',
            trigger: 'blur'
          }
        ],
        chunkSize: [
          {
            required: true,
            message: '每个分片大小（byte）不能为空',
            trigger: 'blur'
          }
        ],
        chunkNum: [
          {
            required: true,
            message: '分片数量不能为空',
            trigger: 'blur'
          }
        ]
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      dialog: {
        title: '',
        flag: ''
      },
      dialogVisible: false,
      form: {},
      formLabelWidth: '100px'
    }
  },
  created () {
    this.selectPage()
  },
  methods: {
    download (row) {
      window.open(axiosBaseUrl + `/api/v1/file/downloadFile?url=${row.fileUrl}`,)
    },
    copyText (text) {
      this.$copyText(text).then(() => {
        this.$notify.success('内容已复制到剪贴板！！！')
      })
    },
    search () {
      this.selectPage()
    },
    resetSearch () {
      this.searchObject = {}
      this.selectPage()
    },
    getCurrent (value) {
      this.pagination.current = value
      this.selectPage()
    },
    getSize (value) {
      this.pagination.size = value
      this.selectPage()
    },
    async addOrSeeOrEdit (title, flag, row) {
      this.dialog.title = title
      this.dialog.flag = flag
      this.dialogVisible = true
      if (flag === 'see' || flag === 'edit') {
        const { data: res } = await fileApi.selectOneOfFile(row.id)
        this.form = res
      } else {
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    },
    removeDialog (row) {
      this.$confirm('是否确认删除？', '确认删除').then(_ => {
        this.remove(row)
      }).catch(_ => {
      })
    },
    async remove (row) {
      const {
        code,
        msg
      } = await fileApi.deleteOfFile(row.id)
      if (code === this.$constant.SUCCESS) {
        this.$message.success(msg)
        await this.selectPage()
      } else {
        this.$message.error(msg)
      }
    },
    selectionChange (value) {
      this.tableSelectData = value
    },
    removeBatchDialog () {
      this.$confirm('是否确认批量删除？', '确认批量删除').then(_ => {
        this.removeBatch()
      }).catch(_ => {
      })
    },
    async removeBatch () {
      const idList = this.tableSelectData.map(item => item.id)
      const {
        code,
        msg
      } = await fileApi.deleteBatchOfFile(idList)
      if (code === this.$constant.SUCCESS) {
        await this.selectPage()
        this.$message.success(msg)
      } else {
        this.$message.error(msg)
      }
    },
    async handleImportFile ({
      code,
      msg
    }) {
      if (code === this.$constant.SUCCESS) {
        this.$message.success(msg)
        await this.selectPage()
      } else {
        this.$message.error(msg)
      }
    },
    async handleExportFile () {
      const confirm = await this.$confirm('是否确认导出？', '确认导出')
      if (confirm) {
        window.open(this.exportUrl)
      }
    },
    async selectPage () {
      this.loadingBtn.tableLoading = true
      const {
        code,
        msg,
        data
      } = await fileApi.selectPageOfFile(this.pagination.current, this.pagination.size, this.searchObject)
      if (code === this.$constant.SUCCESS) {
        this.tableData = data.records
        this.pagination.total = data.total
        this.loadingBtn.tableLoading = false
      } else {
        this.$message.error(msg)
      }
    },
    closeDialog () {
      this.form = {}
      this.dialog.flag = ''
      this.dialog.title = ''
    },
    async submitForm () {
      if (this.dialog.flag === 'see') {
        this.dialogVisible = false
        return
      }
      await this.$refs.form.validate(async (valid) => {
        if (valid) {
          const params = this.form
          if (this.dialog.flag === 'edit') {
            const {
              code,
              msg
            } = await fileApi.updateOfFile(params)
            if (code === this.$constant.SUCCESS) {
              await this.selectPage()
              this.$message.success(msg)
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
          } else {
            const {
              code,
              msg
            } = await fileApi.insertOfFile(params)
            if (code === this.$constant.SUCCESS) {
              await this.selectPage()
              this.$message.success(msg)
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
